// 判断是否已存在

function jshasExis(src) {
  const scripts = document.querySelectorAll('script');
  const hasScripts = [];
  scripts.forEach((it) => {
    it.src == src && hasScripts.push(it);
  });

  return hasScripts;
}

// 加载器单元

class YHLoaderItem {
  constructor(options) {
    this.src = options.src;
    this.id = `yh-loaderitem${options.flag}`;
    this.flag = options.flag;
  }
}

// 加载器

class YHLoader {
  constructor(options) {
    this.items = options.items;
    this.current = 0;
  }

  loading(callBack, next) {
    const that = this;
    if (!next) {
      this.current = 0;
    }

    if (this.current == this.items.length && callBack) {
      callBack({ loaded: true });
      return;
    }

    const { src, flag, id } = this.items[this.current];
    if (window[flag]) {
      console.log(` window scrpit - ${flag} loaded !`);
      this.current += 1;
      that.loading(callBack, true);
    } else {
      const hasScripts = jshasExis(src);
      if (hasScripts.length > 0) {
        hasScripts.forEach((it) => {
          document.body.removeChild(it);
        });
      }
      var scriptElement = document.createElement('script');
      scriptElement.id = id;
      document.body.appendChild(scriptElement);
      scriptElement.addEventListener(
        'load',
        (e) => {
          window[flag] = true;
          console.log(`scrpit - ${flag} loaded !`);
          that.current += 1;
          that.loading(callBack, true);
        },
        false
      );
      scriptElement.addEventListener(
        'error',
        (e) => {
          window[flag] = false;
          console.error(`scrpit - ${src} loaded error!`);
          callBack({ loaded: true, src });
        },
        false
      );
      scriptElement.src = src;
    }
  }
}

// 加载器群

class YHLoaders {
  constructor(options) {
    this.loadersItems = options.loadersItems;
    this.current = 0;
    this.complete = false;
  }
  loading(callBack) {
    // console.log("this.loadersItems = ", this.loadersItems);
    const that = this;
    this.current = 0;
    return new Promise(function (resolve, reject) {
      that.loadersItems.forEach((it, i) => {
        it.loading(({ loaded, src }) => {
          if (loaded) {
            that.current++;
            that.complete = that.current == that.loadersItems.length;
            if (that.complete) {
              if (callBack) {
                callBack(true);
                return;
              }
              resolve({ loaded });
            }
          } else {
            if (callBack) {
              callBack({ loaded, src });
              return;
            }
            reject({ loaded, src });
          }
        });
      });
    });
  }
}

var flag = 0;
//   创建加载器
const createLoaders = function (srcs) {
  //   flag = 0;
  //   创建加载器群参数
  const loadersItems = srcs.map((it) => {
    const items = it.map((it) => {
      //   flag++;
      //   it.flag = `jsLoader${flag}`;
    //   console.log(it);
      it.flag = `JSLoader-${it.src}`;
      //   创建加载器单元
      const item = new YHLoaderItem(it);
      return item;
    });
    //   创建加载器
    const loader = new YHLoader({ items });
    return loader;
  });

  return new YHLoaders({ loadersItems });
};

// 直接加载器

const YHloading = function (srcs, callback) {
  return new Promise(function (resolve, reject) {
    const loader = createLoaders(srcs);
    if (callback) {
      loader.loading(callback);
    } else {
      loader
        .loading()
        .then(function (opts) {
          resolve(opts);
        })
        .catch(function (opts) {
          reject(opts);
        });
    }
  });
};

export default { createLoaders, YHloading };
